package qf.filter;

import qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package qf.filter
 * @Description:
 * @Date 2022/5/23 11:00
 */
@WebFilter(urlPatterns = "/*")
public class PermFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将servletRequest强转为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的地址
        String uri = request.getRequestURI();
        //2.判断用户路径，放行所有静态资源，放行用户登录路径，放行用户注册，商品查询等路径
        //判断路径扩展名，如果是js文件放行，因为js文件与jsp文件相差一个字母，无法使用contains方法（此方法是判断是否包含此字符串）
        HttpSession session = request.getSession();



        if (uri.lastIndexOf(".")>0) {
            String substring = uri.substring(uri.lastIndexOf("."));
            if (substring != null) {


            if (".js".equals(substring)) {
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
            }
        }

        if (uri.contains("/login") || uri.contains("/code")
                || uri.contains("/type")||uri.contains("/goods")
                ||uri.contains("/index")||uri.contains("/cart")
                ||uri.contains("/user") || uri.contains("/register")
                || uri.contains(".css") ||  uri.contains("/admin")
                || uri.contains(".jpg") || uri.contains(".png")
                || uri.contains(".gif") || uri.contains(".eot")
                || uri.contains(".svg") || uri.contains(".ttf")
                || uri.contains(".woff") || uri.contains(".woff2")) {
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.获取session对象
        User user = (User)session.getAttribute("loginUser");

        if (user != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            response.sendRedirect("/goods?method=index");
        }


    }

    @Override
    public void destroy() {

    }
}
